package org.webmev.controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSON;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet(name = "LoginServlet", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {

    private HttpSession session;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        JSONObject jsonObj = JSONObject.fromObject(request.getParameterMap());
        //PrintWriter to send the JSON response back
        PrintWriter out = response.getWriter();
        JSONArray arrayObj = new JSONArray();
        arrayObj = jsonObj.getJSONArray("loginData");
        String userId = arrayObj.getJSONObject(0).getString("userId");
        String password = arrayObj.getJSONObject(0).getString("password");
        if (userId.equals("demo") && password.equals("demo")) {
            session = request.getSession(true);          
            //set content type
            response.setContentType("text/html");
            //Create a JSON object to send response
            JSONObject myObj = new JSONObject();
            myObj.put("success", true);
            myObj.put("userid", session.getId());
            //convert the JSON object to string and send the response back
            out.println(myObj.toString());
            out.close();
        } else {
            
            //set content type
            response.setContentType("text/html");
            //Create a JSON object to send response
            JSONObject myObj = new JSONObject();
            myObj.put("failure", true);
            //convert the JSON object to string and send the response back
            out.println(myObj.toString());
            out.close();
        }
        //Map<String, String[]> params = request.getParameterMap();

        //validateLoginPassword(params);

//        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
//        try {
//            /*
//             * TODO output your page here. You may use following sample code.
//             */
//            out.println("<html>");
//            out.println("<head>");
//            out.println("<title>Servlet LoginServlet</title>");            
//            out.println("</head>");
//            out.println("<body>");
//            out.println("<h1>Servlet LoginServlet at " + request.getContextPath() + "</h1>");
//            out.println("</body>");
//            out.println("</html>");
//        } finally {            
//            out.close();
//        }
    }

    private void validateLoginPassword(Map<String, String[]> p) {
        for (Map.Entry<String, String[]> e : p.entrySet()) {
            String k = e.getKey();
            System.out.println("-------- " + k + "\n");
            String[] vs = e.getValue();
            System.out.println("-------- " + vs[0] + "\n");
            String log = "";
            String pass = "";
            if (k.equals("login") && vs.length == 1) {
                log = vs[0];
//                for (String v : vs) {}
            } else if (k.equals("password") && vs.length == 1) {
                pass = vs[0];
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
